package main.UI;

import main.UI.misc.ErrorHandling;
import main.database.DatabaseException;
import main.database.SQLDatabaseManager;
import main.database.entity.Category;
import main.database.entity.MyEntity;

import javax.swing.*;
import java.awt.event.*;

public class CreateCategoryDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField catField;

    public CreateCategoryDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        setTitle("Новая категория");

        //Ensure the text field always gets the first focus.
        addComponentListener(new ComponentAdapter() {
            @Override
            public void componentShown(ComponentEvent ce) {
                catField.requestFocusInWindow();
            }
        });

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        String typedText = catField.getText();

        if (typedText.equals("")) {
            JOptionPane.showMessageDialog(this,
                    "Вы не ввели имя. \n",
                    "Ошибка",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        SQLDatabaseManager mng = GUI.getSQLManager();
        Category newCat;
        long result;
        try {
            result = mng.getIDByName(MyEntity.CATEGORY, typedText);
            if (result == 0) {
                newCat = mng.saveCategory(typedText, (long) 0);
            }
            else {
                JOptionPane.showMessageDialog(this,
                        "Запись с таким именем уже существует. \n",
                        "Ошибка",
                        JOptionPane.ERROR_MESSAGE);
                catField.requestFocusInWindow();
                return;
            }
        }
        catch (DatabaseException e) {
            ErrorHandling.showError(e, "Ошибка при обращении к базе данных", false);
            dispose();
            return;
        }
        GUI.addNewCategory(newCat.getId(), typedText);
        dispose();
    }


    private void onCancel() {
        dispose();
    }
}
